<?php


namespace app\index\controller;


use app\admin\service\RbacService;
use app\common\controller\CommonController;
use app\common\exception\ParameterFailedException;
use app\common\exception\NotFoundException;
use app\common\model\CartModel;
use app\common\model\ProductModel;
use app\common\model\ProductSkuModel;
use app\common\service\Lang;
use app\common\validate\CartValidate;
use think\facade\Db;
use think\Request;

class CartController extends CommonController
{
    public function getCartList(Request $request)
    {

        $models = (new CartModel())->getUserCartList(
            [
                [
                    'user_id',
                    '=',
                    $request->userModel->getData('id'),
                ],
            ]
        );
        if ($models->isEmpty()) {
            $res = [];
        }
        else {
            $res = $models->toArray();
            foreach ($res as &$modelArr) {
                $modelArr['extend_price'] = $modelArr['count'] * (float)$modelArr['productSkuInfo']['price'];
                self::arrangeProduct($modelArr['productInfo']);
            }
        }

        return retJson(Lang::GETDone, $res);
    }

    public function getCartByIds(Request $request)
    {
        $params             = self::getParam(
            [
                'cart_ids',
            ]
        );
        $params['cart_ids'] = urldecode($params['cart_ids']);
        (new CartValidate())->goCheck(__FUNCTION__, $params);
        if (!is_array($params['cart_ids'])) {
            $params['cart_ids'] = explode(',', $params['cart_ids']);
        }
        $model = (new CartModel())->getUserCartByIds(
            [
                [
                    'id',
                    'in',
                    $params['cart_ids'],
                ],
                [
                    'user_id',
                    '=',
                    $request->userModel->getData('id'),
                ],
            ]
        );
        if (!$model) {
            throw new NotFoundException();
        }
        $res = $model->toArray();
        foreach ($res as &$modelArr) {
            $modelArr['extend_price'] = $modelArr['count'] * (float)$modelArr['productSkuInfo']['price'];
            self::arrangeProduct($modelArr['productInfo']);
        }
        return retJson(Lang::GETDone, $res);
    }

    public function postCart(Request $request)
    {

        $params = self::getParam(
            [
                'product_id',
                'product_sku_id',
                'count',
            ]
        );
        (new CartValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $productModels = (new ProductModel())->where('id', $params['product_id'])->find();
            if (!$productModels) {
                throw new NotFoundException(['msg' => '商品不存在']);
            }
            $productSkuModels = (new ProductSkuModel())->where('id', $params['product_sku_id'])->where(
                'product_id',
                $params['product_id']
            )->find();
            if (!$productSkuModels) {
                throw new NotFoundException(['msg' => '商品规格不存在']);
            }

            $model = (new CartModel())->where('product_id', $params['product_id'])->where(
                'product_sku_id',
                $params['product_sku_id']
            )->where('user_id', $request->userModel->getData('id'))->find();
            if (!$model) {
                if ($params['count'] <= 0) {
                    throw new ParameterFailedException(['购物车数量不能再减了']);
                }
                $model                 = new CartModel();
                $model->product_id     = $params['product_id'];
                $model->product_sku_id = $params['product_sku_id'];
                $model->count          = $params['count'];
                $model->user_id        = $request->userModel->getData('id');
            }
            else {
                if ($params['count'] > 0) {
                    if ($params['count'] + $model->getData('count') > 99) {
                        throw new ParameterFailedException(['购物车该商品已达到最大值']);
                    }
                    $model->count = $params['count'] + $model->getData('count');
                }
                else {
                    if ($model->getData('count') - $params['count'] <= 0) {
                        $model->count       = 0;
                        $model->delete_time = NOW_TIME;
                    }
                    else {
                        $model->count = $model->getData('count') - $params['count'];
                    }
                }
            }
            $model->save();
            Db::commit();
            return retJson(Lang::POSTDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function putCart(Request $request)
    {

        $params = self::getParam(
            [
                'cart_id',
                'product_id',
                'product_sku_id',
                'count',
            ]
        );
        (new CartValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $productModels = (new ProductModel())->where('id', $params['product_id'])->find();
            if (!$productModels) {
                throw new NotFoundException(['msg' => '商品不存在']);
            }
            $productSkuModels = (new ProductSkuModel())->where('id', $params['product_sku_id'])->where(
                'product_id',
                $params['product_id']
            )->find();
            if (!$productSkuModels) {
                throw new NotFoundException(['msg' => '商品规格不存在']);
            }

            $model = (new CartModel())->where('id', $params['cart_id'])
                ->where('product_id', $params['product_id'])
                ->where('product_sku_id', $params['product_sku_id'])
                ->find();
            if (!$model) {
                if ($params['count'] <= 0) {
                    throw new ParameterFailedException(['购物车数量不能再减了']);
                }
                $model                 = new CartModel();
                $model->product_id     = $params['product_id'];
                $model->product_sku_id = $params['product_sku_id'];
                $model->count          = $params['count'];
                $model->user_id        = $request->userModel->getData('id');
            }
            else {
                if ($params['count'] > 0) {
                    if ($params['count'] + $model->getData('count') > 99) {
                        throw new ParameterFailedException(['购物车该商品已达到最大值']);
                    }
                    $model->count = $params['count'] + $model->getData('count');
                }
                else {
                    if ($model->getData('count') + $params['count'] <= 0) {
                        $model->count       = 0;
                        $model->delete_time = NOW_TIME;
                    }
                    else {
                        $model->count = $model->getData('count') + $params['count'];
                    }
                }
            }
            $model->save();
            Db::commit();
            return retJson(Lang::PUTDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function deleteCart(Request $request)
    {

        $params = self::getParam(['cart_ids']);
        (new CartValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            if (!is_array($params['cart_ids'])) {
                $params['cart_ids'] = explode(',', $params['cart_ids']);
            }
            $models = CartModel::whereIn('id', $params['cart_ids'])->where(
                'user_id',
                $request->userModel->getData('id')
            )->select();
            if (count($models) !== count($params['cart_ids'])) {
                throw new ParameterFailedException();
            }

            foreach ($models as $model) {
                $model->delete_time = NOW_TIME;
                $model->save();
            }

            Db::commit();

            return retJson(Lang::DELETEDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }
}